<template>
  <div class="home-container flex-y">
    <div class="title flex-center">{{ title }}</div>
    <div class="page-content flex1">
      <el-row class="content-wrap flex">
        <el-col :span="4" class="left-wrap">
          <el-menu
            :default-active="String(currentActiveIndex)"
            class="menu-vertical"
            active-text-color="#e16531"
            @select="handleSelect"
          >
            <el-menu-item
              v-for="(item, i) in productList"
              :key="item.product_code"
              :index="String(i)"
            >
              <i class="el-icon-menu"></i>
              <template #title>{{ item.product_code }}</template>
            </el-menu-item>
          </el-menu>
        </el-col>
        <el-col :span="20" class="right-wrap flex1">
          <div class="table-bar">
            <h3>{{ versionName }}</h3>
            <div class="btn-wrap">
              <el-button
                type="warning"
                icon="el-icon-circle-plus-outline"
                round
                :disabled="disabledBtn"
                @click="handleVersionAdd"
                >新建版本</el-button
              >
              <el-button
                type="warning"
                :icon="isLocked ? 'el-icon-unlock' : 'el-icon-lock'"
                round
                :disabled="disabledBtn"
                @click="handleLockChange(isLocked)"
                >{{ isLocked ? '解锁' : '锁定' }}版本</el-button
              >
              <el-button
                type="warning"
                :icon="isTested ? 'el-icon-folder-delete' : 'el-icon-folder-checked'"
                round
                :disabled="disabledBtn"
                @click="handleTestChange(isTested)"
                >测试{{ isTested ? '不' : '' }}通过</el-button
              >
              <el-button
                type="warning"
                icon="el-icon-download"
                round
                :disabled="disabledBtn"
                @click="handleVersionDown"
                >下载
              </el-button>
              <el-button
                type="warning"
                icon="el-icon-upload"
                round
                :disabled="disabledBtn"
                @click="handleVersionUpload"
                >上传</el-button
              >
            </div>
          </div>
          <div class="table-content">
            <el-table
              ref="singleTable"
              :data="tableList"
              highlight-current-row
              style="width: 100%"
              @current-change="handleCurrentChange"
            >
              <el-table-column type="index" width="50" label="序号"></el-table-column>
              <el-table-column property="version_number" label="版本号"></el-table-column>
              <el-table-column
                property="lock_status"
                label="锁定状态"
                :formatter="formatterTable"
              ></el-table-column>
              <el-table-column
                property="test_status"
                label="测试状态"
                :formatter="formatterTable"
              ></el-table-column>
              <el-table-column
                property="is_uploading"
                label="是否上传"
                :formatter="formatterTable"
              ></el-table-column>
              <el-table-column property="source_version" label="源版本"></el-table-column>
              <el-table-column property="ip" label="主机IP"> </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
  <el-dialog
    v-model="addDialogVisible"
    title="新建版本"
    :destroy-on-close="true"
    :before-close="handleAddCancel"
  >
    <el-form ref="addRef" :model="addDialogForm" class="form-content">
      <el-form-item
        label="新增的版本类型"
        prop="version_type"
        :rules="[
          {
            required: true,
            message: '请选择版本类型',
            trigger: 'change',
          },
        ]"
      >
        <el-radio-group v-model="addDialogForm.version_type">
          <el-radio :label="1">主版本</el-radio>
          <el-radio :label="2">小版本</el-radio>
          <el-radio :label="3">修复版本</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="备注"
        prop="remark"
        :rules="[
          {
            required: true,
            message: '请填写备注',
            trigger: 'blur',
          },
        ]"
      >
        <el-input v-model="addDialogForm.remark" type="textarea" :rows="2" placeholder="请输入内容">
        </el-input>
      </el-form-item>
      <el-form-item class="dialog-footer">
        <el-button type="warning" @click="handleAddSubmit">确定</el-button>
        <el-button @click="handleAddCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, watch, computed, ref, Ref } from 'vue';
import {
  ElMenu,
  ElMenuItem,
  ElRow,
  ElCol,
  ElTable,
  ElTableColumn,
  ElButton,
  ElDialog,
  ElRadioGroup,
  ElRadio,
  ElInput,
  ElForm,
  ElFormItem,
  ElMessage,
  ElMessageBox,
} from 'element-plus';
import {
  getVersionProductList,
  getVersionVersionList,
  postVersionVersionAdd,
  postVersionLockStatus,
} from '/@/api/product';

export default defineComponent({
  name: 'Home',
  components: {
    ElMenu,
    ElMenuItem,
    ElRow,
    ElCol,
    ElTable,
    ElTableColumn,
    ElButton,
    ElDialog,
    ElRadioGroup,
    ElRadio,
    ElInput,
    ElForm,
    ElFormItem,
  },
  setup() {
    const data = {
      title: '高盈产品版本管理',
    };
    const addRef = ref<typeof ElForm>();
    const refData = reactive({
      currentActiveIndex: 0,
      currentSelectVersionInfo: {},
      currentSelectVersionNumber: '',
      addDialogVisible: false,
      addDialogForm: {
        version_type: '',
        remark: '',
      },
      productList: [{}],
      tableList: [{}],
    });

    let versionName = computed(() => {
      return refData.productList[refData.currentActiveIndex].product_description;
    });

    let disabledBtn = computed(() => {
      return refData.currentSelectVersionNumber === '';
    });

    let isLocked = computed(() => {
      return (
        refData.currentSelectVersionInfo &&
        String(refData.currentSelectVersionInfo.lock_status) === '1'
      );
    });

    let isTested = computed(() => {
      return (
        refData.currentSelectVersionInfo &&
        String(refData.currentSelectVersionInfo.test_status) === '1'
      );
    });

    /**
     * 获取产品列表
     */
    const getProductData = async () => {
      const { product_list } = await getVersionProductList();
      refData.productList = product_list;
    };

    /**
     * 获取版本列表
     * @param productCode {string} 产品代码
     */
    const getVersionData = async (productCode) => {
      const params = {
        product_code: productCode,
      };
      const { version_list } = await getVersionVersionList(params);
      refData.tableList = version_list;
    };

    const handleSelect = (index) => {
      refData.currentActiveIndex = index;
    };

    const handleCurrentChange = (currentRow) => {
      refData.currentSelectVersionInfo = currentRow;
      refData.currentSelectVersionNumber = currentRow.version_number;
    };

    const handleVersionAdd = () => {
      refData.addDialogVisible = true;
    };

    const handleAddSubmit = async () => {
      const valid: boolean | undefined = await addRef.value?.validate();
      console.log(valid);
      if (valid) {
        try {
          const productCode = refData.productList[refData.currentActiveIndex].product_code;
          const data = {
            ...refData.addDialogForm,
            product_code: productCode,
            source_version: refData.currentSelectVersionInfo?.source_version,
          };
          await postVersionVersionAdd(data);
          await getVersionData(productCode);
        } catch (e) {
          // do catch
          console.log(e);
        }
      }
    };

    const handleAddCancel = () => {
      refData.addDialogVisible = false;
      addRef.value?.resetFields();
      ElMessage.info('已取消');
    };

    const handleLockChange = (isLocked) => {
      const { currentSelectVersionInfo, currentActiveIndex, productList } = refData;
      ElMessageBox.confirm(
        `${isLocked ? '解锁' : '锁定'} ${currentSelectVersionInfo.version_number} 版本？`,
        '操作提示',
        {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          confirmButtonClass: 'warning',
        },
      )
        .then(() => {
          const params = {
            version_number: currentSelectVersionInfo.version_number,
            product_code: productList[currentActiveIndex].product_code,
            status: isLocked ? '0' : '1',
          };
          postVersionLockStatus(params)
            .then(() => {
              getVersionData(refData.productList[refData.currentActiveIndex].product_code);
              ElMessage.info('操作成功');
            })
            .catch(() => {
              // do catch
            });
        })
        .catch(() => {
          ElMessage.info('已取消');
        });
    };

    const handleTestChange = (isTested) => {
      const { currentSelectVersionInfo, currentActiveIndex, productList } = refData;
      console.log(currentSelectVersionInfo.version_number);
      ElMessageBox.confirm(
        `${currentSelectVersionInfo.version_number} 版本测试${isTested ? '不' : ''}通过？`,
        '操作提示',
        {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        },
      )
        .then(() => {
          const params = {
            version_number: currentSelectVersionInfo.version_number,
            product_code: productList[currentActiveIndex].product_code,
            status: isLocked ? '0' : '1',
          };
          postVersionLockStatus(params)
            .then(() => {
              getVersionData(refData.productList[refData.currentActiveIndex].product_code);
              ElMessage.info('操作成功');
            })
            .catch(() => {
              // do catch
            });
        })
        .catch(() => {
          ElMessage.info('已取消');
        });
    };

    const handleVersionDown = () => {
      const { currentSelectVersionInfo, currentActiveIndex, productList } = refData;
      const params = {
        version_number: currentSelectVersionInfo.version_number,
        product_code: productList[currentActiveIndex].product_code,
      };
      let a = document.createElement('a');
      // 模拟a链接下载
      a.setAttribute(
        'href',
        `http://172.16.55.21:9110/version/downloads?version_number=${params.version_number}&product_code=${params.product_code}`,
      );
      document.body.appendChild(a);
      a.click();
    };

    const handleVersionUpload = () => {
      console.log('handleVersionUpload');
    };

    /**
     * 格式化渲染数据
     * @param row {Object} 行数据
     * @param column {Object} 列数据
     * @param value {*} 被格式化数据
     */
    const formatterTable = (row, column, value): string => {
      if (column.property === 'lock_status') {
        switch (String(value)) {
          case '0':
            return '未锁定';
          case '1':
            return '锁定';
          default:
            return '';
        }
      } else if (column.property === 'test_status') {
        switch (String(value)) {
          case '0':
            return '未测';
          case '1':
            return '通过';
          case '2':
            return '未通过';
          default:
            return '';
        }
      } else if (column.property === 'is_uploading') {
        switch (String(value)) {
          case '0':
            return '否';
          case '1':
            return '是';
          default:
            return '';
        }
      } else {
        return value;
      }
    };

    onMounted(async () => {
      await getProductData();
      await getVersionData(refData.productList[refData.currentActiveIndex].product_code);
    });

    watch([() => refData.currentActiveIndex], ([val]) => {
      getVersionData(refData.productList[val].product_code);
    });

    return {
      ...data,
      versionName,
      disabledBtn,
      isLocked,
      isTested,
      addRef,
      ...toRefs(refData),
      handleSelect,
      formatterTable,
      handleCurrentChange,
      handleVersionAdd,
      handleTestChange,
      handleLockChange,
      handleVersionDown,
      handleVersionUpload,
      handleAddSubmit,
      handleAddCancel,
    };
  },
});
</script>

<style scoped lang="scss">
.home-container {
  height: 100%;
}
.title {
  height: 60px;
  font-size: 20px;
  font-weight: bold;
  flex-shrink: 0;
  @include bottom-line($gray-1);
}
.page-content {
  padding: 10px;
}
.content-wrap {
  height: 100%;
}
.left-wrap {
  //height: 100%;
  height: calc(100vh - 160px);
  overflow: auto;
  min-width: 150px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.6);
}
.right-wrap {
  margin-left: 20px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.6);
}
.table-bar {
  padding: 0 10px 10px;
  h3 {
    color: $color-6;
  }
}
.table-content {
  padding: 0 10px;
  height: calc(100vh - 270px);
  .el-table {
    height: 100%;
    border-radius: 5px;
  }
}
.el-menu {
  background-color: transparent;
}
.add-dialog {
  border-radius: 5px !important;
}
.el-radio-group {
  width: 100%;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>
